<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 站号选择 -->
      <el-select v-model="listQuery.stationNumber" :placeholder="$t('equipment.stationNumber')" class="filter-item" clearable="" style="width: 200px">
        <el-option v-for="station in stationOptions" :key="station.stationName" :label="station.stationName+'_'+station.stationNumber" :value="station.stationNumber" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading1" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownExcel">
        {{ $t('common.exportExcel') }}
      </el-button>
      <upload-excel-component class="filter-item" :on-success="handleSuccess" :before-upload="beforeUpload" />
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      row-key="id"
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="$t('equipment.stationNumber')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.alarmCode')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.alarmCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.alarmText')" width="" align="center">
        <template slot-scope="{row}">
          <span>{{ row.alarmText }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.alarmType')" width="" align="center">
        <template slot-scope="{row}">
          <el-tag
            :type="row.alarmType === 'info'?'info':row.alarmType === 'warn'?'warning':row.alarmType === 'error'?'danger':'danger'"
            effect="light"
          > {{ row.alarmType }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="150px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.stationNumber')">
          <el-select v-model="temp.stationNumber" :placeholder="$t('equipment.stationNumber')" class="filter-item" style="width: 200px">
            <el-option v-for="item in stationOptions" :key="item.stationNumber" :label="item.stationName+'_'+item.stationNumber" :value="item.stationNumber" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('equipment.alarmCode')">
          <el-input v-model="temp.alarmCode" :placeholder="$t('equipment.alarmCode')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.alarmText')">
          <el-input v-model="temp.alarmText" clearable :placeholder="$t('equipment.alarmText')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.alarmType')">
          <el-select v-model="temp.alarmType" :placeholder="$t('equipment.alarmType')" class="filter-item" clearable="" style="width: 200px">
            <el-option v-for="alarm in alarmOptions" :key="alarm.key" :label="alarm.label" :value="alarm.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getStationListEx, importExcel, getEquipmentAlarmDefsList, creatEquipmentAlarmDefsList, updateEquipmentAlarmDefsList, deleteEquipmentAlarmDefsList } from '@/api/equipment'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import UploadExcelComponent from '@/components/UploadExcel'

export default {
  name: 'EquipmentAlarmDefs',
  components: {
    Pagination,
    UploadExcelComponent
  },
  directives: { waves, elDragDialog },
  data() {
    return {
      stationOptions: [],
      alarmOptions: [{ label: i18n.t('common.tip'), key: 'info', color: 'black' },
        { label: i18n.t('common.warn'), key: 'warn', color: 'blue' },
        { label: i18n.t('common.error'), key: 'error', color: 'red' }],
      dialogForm: false,
      fileUploadBtnText: '导入',
      uploadBtnIcon: 'el-icon-upload2',
      list: [],
      total: 0,
      fileList: [],
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        lineNumber: '',
        stationNumber: '',
        sort: '+processNumber'
      },
      temp: {
        stationNumber: '',
        alarmCode: '',
        alarmText: '',
        lineNumber: this.$store.getters.lineNumber,
        alarmType: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      downloadLoading: false,
      downloadLoading1: false
    }
  },
  created() {
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    this.listQuery.lineId = this.$store.getters.lineId
    this.getStationOptions()
    this.getList()
  },
  methods: {
    // 获取工站选项
    getStationOptions() {
      this.listLoading = true
      this.stationOptions = []
      getStationListEx(this.listQuery).then(response => {
        this.stationOptions = response.data.stations
        this.listLoading = false
      })
    },
    // 判断线体ID是否为空
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取清单
    getList() {
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getEquipmentAlarmDefsList(this.listQuery).then(response => {
          this.list = response.data.equipmentAlarmDefs
          this.total = response.data.total
          this.listLoading = false
        })
      }
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 上传文件大小
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 拿到excel数据
    handleSuccess({ results }) {
      results.forEach(item => {
        item.lineNumber = this.listQuery.lineNumber
        item.stationNumber = item.工站号
        item.alarmCode = item.报警代码
        item.alarmText = item.报警信息
        item.alarmType = item.报警类型
        delete item.工站号
        delete item.报警代码
        delete item.报警信息
        delete item.报警类型
      })
      importExcel(results).then(res => {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.CREAT_SUCCESS'),
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
        .catch(err => {
          console.error(err)
        })
    },
    // 初始化创建信息
    resetTemp() {
      this.temp.stationNumber = this.stationOptions.length > 0 ? this.stationOptions[0].stationNumber : ''
      this.stationOptions.forEach(e => {
        if (e.stationNumber === this.listQuery.stationNumber) {
          this.temp.stationNumber = e.stationNumber
          return
        }
      })
      this.temp.alarmCode = ''
      this.temp.alarmText = ''
      this.temp.alarmType = ''
    },
    // 新建一个数据
    handleCreate() {
      if (this.isEmptyLineId() === false) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.stationOptions.forEach(p => {
            if (p.stationNumber === this.temp.stationNumber) {
              this.temp.stationNumber = p.stationNumber
            }
          })
          creatEquipmentAlarmDefsList(this.temp).then(response => {
            this.list.push(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.stationOptions.forEach(p => {
            if (p.stationNumber === this.temp.stationNumber) {
              this.temp.stationNumber = p.stationNumber
            }
          })
          updateEquipmentAlarmDefsList(this.temp).then(response => {
            const index = this.list.findIndex(v => v.stationNumber === this.temp.stationNumber)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteEquipmentAlarmDefsList(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 下载excle模板
    handleDownExcel() {
      this.downloadLoading1 = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('equipment.stationNumber'),
          i18n.t('equipment.alarmCode'),
          i18n.t('equipment.alarmText'),
          i18n.t('equipment.lineNumber'),
          i18n.t('equipment.alarmType')]
        const filterVal = []
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '设备报警定义' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading1 = false
      })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('equipment.stationNumber'),
          i18n.t('equipment.alarmCode'),
          i18n.t('equipment.alarmText'),
          i18n.t('equipment.alarmType')]
        const filterVal = ['stationNumber', 'alarmCode', 'alarmText', 'alarmType']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '设备报警定义' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.diag{
::v-deep .el-col-24{
  width: 14%!important;
    line-height: 25px!important;
}
::v-deep .el-dialog{
  width: 40vw!important;
}
}
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
